import os
import datetime

from sqlalchemy import create_engine, Column, Integer, String, Date, Double
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# 建立数据库连接
db_url = "mysql+pymysql://root:919191@192.168.1.191:3306/vw_dj"
engine = create_engine(db_url, echo=True)  # echo=True可用于显示SQL语句执行情况
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()

def readFolder():
    file_info_list = []  # 用于存储文件信息的列表
    # 指定要读取的文件夹路径
    folder_path = r'C:\Users\metype\Desktop\知识库文件20230925'

    # 获取文件夹中所有文件的列表
    file_list = os.listdir(folder_path)

    # 遍历文件列表
    for file_name in file_list:
        # 使用os.path.join获取文件的完整路径
        file_path = os.path.join(folder_path, file_name)

        # 检查文件是否是普通文件
        if os.path.isfile(file_path):
            # 获取文件的名称和后缀
            file_name, file_extension = os.path.splitext(file_name)

            # 获取文件大小（以字节为单位）
            file_size = os.path.getsize(file_path)
            file_size_mb = round(file_size / (1024 * 1024), 2)  # 将字节转换为兆字节

            # 封装文件信息到字典
            file_info = {
                "fileName": file_name,
                "fileExtension": file_extension,
                "fileSize": str(file_size_mb) + "MB"
            }

            # 将文件信息添加到列表
            file_info_list.append(file_info)
    return file_info_list


def saveFileInfo():
    # 关键词 entity
    class attachment(Base):
        __tablename__ = 'j_attachment'
        attachment_id = Column(Integer, primary_key=True)
        type = Column(String)
        title = Column(String)
        suffix = Column(String)
        category_first = Column(Integer)
        file_size = Column(String)
        url = Column(String)
        delete_status = Column(Integer)
        gmt_create = Column(Date)
        gmt_modified = Column(Date)

    for folder in readFolder():
        new_attachment = attachment(type=4, title=folder["fileName"], suffix=folder["fileExtension"], category_first=6, file_size=folder["fileSize"],
                                      url=folder["fileName"]+folder["fileExtension"], delete_status=0, gmt_create=datetime.datetime.now(), gmt_modified=datetime.datetime.now() )
        session.add(new_attachment)
        session.commit()


def main():
    saveFileInfo()


if __name__ == '__main__':
    main()
